#include "stm32f10x.h"                  // Device header
#include "LED.h"

void myADC_Init(void)
{
	// 开启时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	// 设置ADC时钟
	RCC_ADCCLKConfig(RCC_PCLK2_Div6);
	// GPIO初始化
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_7;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);		
	// ADC初始化
	ADC_InitTypeDef myADC_InitStructure;
	myADC_InitStructure.ADC_ContinuousConvMode = ENABLE;
	myADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
	myADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;			// 不使用外部触发, 软件触发
	myADC_InitStructure.ADC_Mode = ADC_Mode_Independent;							// 单ADC模式
	myADC_InitStructure.ADC_NbrOfChannel = 4;										// 4个通道转换
	myADC_InitStructure.ADC_ScanConvMode = ENABLE;
	ADC_Init(ADC1, &myADC_InitStructure);
	
										// 软件触发
	ADC_RegularChannelConfig(ADC1, ADC_Channel_0, 1, ADC_SampleTime_55Cycles5);
	ADC_RegularChannelConfig(ADC1, ADC_Channel_1, 2, ADC_SampleTime_55Cycles5);
	ADC_RegularChannelConfig(ADC1, ADC_Channel_2, 3, ADC_SampleTime_55Cycles5);
	ADC_RegularChannelConfig(ADC1, ADC_Channel_7, 4, ADC_SampleTime_55Cycles5);

	// 启用ADC中断
	ADC_ITConfig(ADC1, ADC_IT_EOC, ENABLE);
	// 开启ADC, 且, 和DMA配合
	ADC_DMACmd(ADC1, ENABLE);
	ADC_Cmd(ADC1, ENABLE);
	//ADC校准, 先打开再校准
	ADC_ResetCalibration(ADC1);
	while(ADC_GetResetCalibrationStatus(ADC1) == SET);
	ADC_StartCalibration(ADC1);
	while(ADC_GetCalibrationStatus(ADC1) == SET);
	ADC_SoftwareStartConvCmd(ADC1, ENABLE);
	
	// NVIC初始化
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	NVIC_InitTypeDef NVIC_InitStructure;
	NVIC_InitStructure.NVIC_IRQChannel = ADC1_2_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
	NVIC_Init(&NVIC_InitStructure);
}

void ADC1_2_IRQHandler(void)
{
	if (ADC_GetITStatus(ADC1, ADC_IT_EOC) == RESET)
	{
		LED1_ON();
		ADC_ClearITPendingBit(ADC1, ADC_IT_EOC);
	}
}
